package com.yehun.admin.controller;

import com.yehun.admin.models.JsonResult;
import com.yehun.admin.models.PageConfig;
import com.yehun.admin.models.RoleModel;
import com.yehun.entity.PagerEntity;
import com.yehun.entity.Role;
import com.yehun.entity.Route;
import com.yehun.enums.StatusEnum;
import com.yehun.exception.ErrorException;
import com.yehun.service.RoleService;
import com.yehun.service.RouteService;
import com.yehun.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 用户角色
 */
@Controller
@RequestMapping(value = "role")
public class RoleController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(RoleController.class);

    private final RoleService roleService;
    private final RouteService routeService;

    @Autowired
    public RoleController(RoleService roleService, RouteService routeService) {
        this.roleService = roleService;
        this.routeService = routeService;
    }

    @RequestMapping(value = { "", "index", "list" }, name = "角色列表")
    public String list() {
        return "role/list";
    }

    @ResponseBody
    @RequestMapping(value = "listAjax", name = "角色列表Ajax")
    public PageConfig listAjax() {
        int pageIndex = ParamUtils.getPageIndex();
        int pageSize = ParamUtils.getPageSize();
        PagerEntity<Role> pager = roleService.listPager(pageIndex, pageSize);
        return PageConfig.mapper(pager);
    }

    @RequestMapping(value = "add", name = "角色添加")
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("role/add");
        view.addObject("role", new RoleModel());
        view.addObject("statuses", EnumUtils.getSelect(StatusEnum.class));
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "addAjax", method = RequestMethod.POST, name = "角色添加Post")
    public JsonResult addAjax(RoleModel roleModel) {
        JsonResult jsonResult = new JsonResult();
        logger.info("role.add, roleModel={}", JsonUtils.serialize(roleModel));
        Role role = MapperUtils.map(roleModel, Role.class);
        logger.info("role.add, roleEntity={}", JsonUtils.serialize(role));
        int row = roleService.save(role);
        logger.info("role add is row={}", row);
        boolean ret = row > 0;
        jsonResult.setCode(ret ? 0 : 1);
        jsonResult.setMessage(ret ? "添加成功" : "添加失败");
        return jsonResult;
    }

    @RequestMapping(value = "edit", method = RequestMethod.GET, name = "角色修改")
    public ModelAndView edit(int roleId) {
        ModelAndView view = new ModelAndView("role/edit");
        view.addObject("statuses", EnumUtils.getSelect(StatusEnum.class));
        Role role = roleService.get(roleId);
        view.addObject("role", role);
        view.addObject("message", role == null ? "角色不存在" : "");
        return view;
    }

    @RequestMapping(value = "edit", method = RequestMethod.POST, name = "角色修改post")
    public JsonResult edit(RoleModel roleModel) {
        JsonResult jsonResult = new JsonResult();
        Role role = roleService.get(roleModel.getId());
        if (role == null) {
            jsonResult.setCode(1);
            jsonResult.setMessage("角色不存在");
            return jsonResult;
        }
        Role roleEntity = MapperUtils.map(roleModel, Role.class);
        int row = roleService.update(roleEntity);
        boolean ret = row > 0;
        jsonResult.setCode(ret ? 0 : 1);
        jsonResult.setMessage(ret ? "修改成功" : "修改失败");
        return jsonResult;
    }


    @RequestMapping(value = "editPermission", method = RequestMethod.GET, name = "角色权限修改")
    public ModelAndView editPermission(@RequestParam("roleId") int roleId) {
        ModelAndView view = new ModelAndView("role/editPermission");
        Role role = roleService.get(roleId);
        view.addObject("role", role);
        List<Route> routes = routeService.listAll();
        List<Map<String, Object>> mapList = new LinkedList<>();
        Map<String, Object> map;
        for (Route route : routes) {
            if(StringUtils.isEmpty(route.getRemark())) continue;
            map = new LinkedHashMap<>();
            map.put("url", route.getUrl());
            map.put("remark", route.getRemark());
            map.put("value", route.getValue());
            map.put("checked", BitOperUtils.exists(role.getPermission(), route.getValue()));
            mapList.add(map);
        }
        view.addObject("permissions", mapList);
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "editPermission", method = RequestMethod.POST, name = "角色权限修改post")
    public JsonResult editPermission(@RequestParam("roleId") int roleId, @RequestParam("values[]") String[] values) {
        logger.info("roleId={}", roleId);
        logger.info("values.length={}", values.length);
        Long roleValue = 0L;
        Long tmpValue;
        for (String value : values) {
            tmpValue = ParseUtils.parseLong(value);
            if (!BitOperUtils.exists(roleValue, tmpValue)) {
                roleValue = BitOperUtils.insert(roleValue, tmpValue);
            }
        }
        logger.info("userValue={}", roleValue);
        JsonResult jsonResult = new JsonResult();
        int row = roleService.updatePermission(roleId, roleValue);
        boolean ret = row > 0;
        jsonResult.setCode(ret ? 0 : 1);
        jsonResult.setMessage(ret ? "修改成功" : "修改失败");
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping(value = "remove", name = "角色删除")
    public JsonResult remove() {
        Integer[] idArray = ParamUtils.getIntArray("idArray", ",");
        logger.info("idArray.length={}", idArray.length);
        JsonResult jsonResult = new JsonResult();
        try {
            int row = roleService.remove(idArray);
            boolean ret = row > 0;
            jsonResult.setCode(ret ? 0 : 1);
            jsonResult.setMessage(ret ? "删除成功" : "删除失败");
        } catch (ErrorException e) {
            jsonResult.setCode(-1);
            jsonResult.setMessage(e.getMessage());
        }
        return jsonResult;
    }


}
